package com.mercadoutils.controller;

import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.Meli;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.listeners.SesionListener;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;

@Controller
public class QuestionController {

	@RequestMapping("/ItemQuestion.html")
	 public String doRedirect(@RequestParam (value="id") String id,@RequestParam (value="title") String title,Model model) throws AuthorizationFailure, MeliException, IOException
	 {
		 model.addAttribute("title",title.replaceAll("space"," "));		
		 
		 HttpSession session = SesionListener.getSession();
	     Meli m = (Meli) session.getAttribute("meli");
	               
        FluentStringsMap params = new FluentStringsMap();
        params.add("item_id", id);
        params.add("access_token", m.getAccessToken());
        Response r = m.get("/questions/search",params);
        
		String resultado = r.getResponseBody().toString(); 
		JsonElement jelement = new JsonParser().parse(resultado); 
	    JsonObject  jobject = jelement.getAsJsonObject();
	    
	    JsonArray jarray = jobject.getAsJsonArray("questions");
//	    System.out.println(jarray.get(0).getAsJsonObject().get("text"));
//	    System.out.println(resultado);

	    String response = "";
	    for(int i = 0 ; i<jarray.size();i++){
	    	
	    	if(jarray.get(i).getAsJsonObject().get("status").getAsString().equals("ANSWERED"))
	    		response+="<h3>Pregunta: "+jarray.get(i).getAsJsonObject().get("text").getAsString()+"</h3><div>"+jarray.get(i).getAsJsonObject().get("answer").getAsJsonObject().get("text").getAsString()+"</div>";
	    	else
	    		response+="<h3>Pregunta: "+jarray.get(i).getAsJsonObject().get("text").getAsString()+"</h3><div><textarea id=\""+jarray.get(i).getAsJsonObject().get("id").getAsString()+"\" rows=\"1\" cols=\"99999\" style=\"width:1000px; height:100px;\"></textarea><button onclick=\"answerQuestion('"+jarray.get(i).getAsJsonObject().get("id").getAsString()+"')\">Responder</button></div>";
	    }
	    
	    model.addAttribute("relleno", response);
	    model.addAttribute("nombre",session.getAttribute("nombre"));
	    model.addAttribute("apellido",session.getAttribute("apellido"));
	    model.addAttribute("role",session.getAttribute("role"));
	    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		 return "ItemQuestions";
	 }
	
	@RequestMapping("/QuestionAnswer.html")
	 public String doAnswer(@RequestParam (value="id") String id,@RequestParam (value="text") String text,@RequestParam (value="url") String url,@RequestParam (value="title") String title,Model model) throws MeliException, IOException, InterruptedException
	 {
		 HttpSession session = SesionListener.getSession();
	     Meli m = (Meli) session.getAttribute("meli");
	     FluentStringsMap params = new FluentStringsMap();
	     params.add("access_token", m.getAccessToken());
//	     System.out.println("entro");
//	     System.out.println("id:"+id);
//	     System.out.println("text:"+text);
//	     System.out.println("title:"+title);
//	     System.out.println("url:"+url);
//	     System.out.println("url:"+url.substring(34,url.length()-1));
	     
	     
	     Response r = m.post("/answers", params, "{\"question_id\":"+id+",\"text\":\""+text+"\"}");
	     
	     System.out.println(r.getResponseBody().toString());
		    model.addAttribute("nombre",session.getAttribute("nombre"));
		    model.addAttribute("apellido",session.getAttribute("apellido"));
		    model.addAttribute("role",session.getAttribute("role"));
		    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		    Thread.currentThread().sleep(2000);
		return "redirect:"+url+"&title="+title;
	 }
	
	@RequestMapping("/QuestionAnswerAll.html")
	 public String doAnswerAll(@RequestParam (value="id") String id,@RequestParam (value="text") String text,@RequestParam (value="url") String url,Model model) throws MeliException, IOException, InterruptedException
	 {
		 HttpSession session = SesionListener.getSession();
	     Meli m = (Meli) session.getAttribute("meli");
	     FluentStringsMap params = new FluentStringsMap();
	     params.add("access_token", m.getAccessToken());
//	     System.out.println("entro");
//	     System.out.println("id:"+id);
//	     System.out.println("text:"+text);
//	     System.out.println("title:"+title);
//	     System.out.println("url:"+url);
//	     System.out.println("url:"+url.substring(34,url.length()-1));
	     
	     
	     Response r = m.post("/answers", params, "{\"question_id\":"+id+",\"text\":\""+text+"\"}");
	     
	     System.out.println(r.getResponseBody().toString());
		    model.addAttribute("nombre",session.getAttribute("nombre"));
		    model.addAttribute("apellido",session.getAttribute("apellido"));
		    model.addAttribute("role",session.getAttribute("role"));
		    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		    Thread.currentThread().sleep(2000);
		return "redirect:"+url;
	 }
	
	@RequestMapping("/AllQuestion.html")
	 public String doRedirectAllQuestion(Model model) throws AuthorizationFailure, MeliException, IOException
	 {
		 
		 HttpSession session = SesionListener.getSession();
	     Meli m = (Meli) session.getAttribute("meli");
	               
       FluentStringsMap params = new FluentStringsMap();
       params.add("status", "unanswered");
       params.add("access_token", m.getAccessToken());
       Response r = m.get("/my/received_questions/search",params);
       
		String resultado = r.getResponseBody().toString(); 
		JsonElement jelement = new JsonParser().parse(resultado); 
	    JsonObject  jobject = jelement.getAsJsonObject();
	    System.out.println(jobject.toString());
	    
	    JsonArray jarray = jobject.getAsJsonArray("questions");
	    
//	    System.out.println("Resultado: \n"+resultado+"\nfin resultado");
//	    for(int i =0 ; i<jarray.size();i++ )
//	    	System.out.println(jarray.get(i).getAsJsonObject().toString());


	    String response = "";
	    String items[]= new String[1000];
	    int contador=0;
	    for(int i = 0 ; i<jarray.size();i++){
	    	if(!controlarArray(jarray.get(i).getAsJsonObject().get("item_id").getAsString(),items,contador)){
	    		Response r2 = m.get("/items/"+jarray.get(i).getAsJsonObject().get("item_id").getAsString());
	    		String resultado2 = r2.getResponseBody().toString(); 
	    		JsonElement jelement2 = new JsonParser().parse(resultado2); 
	    	    JsonObject  jobject2 = jelement2.getAsJsonObject();
	    	    String titulo = jobject2.get("title").toString();
	    		response+="<h3>Producto:"+titulo+" - Pregunta: "+jarray.get(i).getAsJsonObject().get("text").getAsString()+"</h3><div><textarea id=\""+jarray.get(i).getAsJsonObject().get("id").getAsString()+"\" rows=\"1\" cols=\"99999\" style=\"width:1000px; height:100px;\"></textarea><button onclick=\"answerQuestion('"+jarray.get(i).getAsJsonObject().get("id").getAsString()+"')\">Responder</button></div>";
	    		items[contador]=jarray.get(i).getAsJsonObject().get("item_id").getAsString();
	    		contador++;
	    		for(int j=i+1;j<jarray.size();j++)
	    			if(jarray.get(i).getAsJsonObject().get("item_id").getAsString().equals(jarray.get(j).getAsJsonObject().get("item_id").getAsString()))
	    				response+="<h3>Producto:"+titulo+" - Pregunta: "+jarray.get(j).getAsJsonObject().get("text").getAsString()+"</h3><div><textarea id=\""+jarray.get(j).getAsJsonObject().get("id").getAsString()+"\" rows=\"1\" cols=\"99999\" style=\"width:1000px; height:100px;\"></textarea><button onclick=\"answerQuestion('"+jarray.get(j).getAsJsonObject().get("id").getAsString()+"')\">Responder</button></div>";
	    	}
	    }
	    
	    model.addAttribute("relleno", response);
	    model.addAttribute("nombre",session.getAttribute("nombre"));
	    model.addAttribute("apellido",session.getAttribute("apellido"));
	    model.addAttribute("role",session.getAttribute("role"));
	    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		 return "AllQuestions";
	 }
	
	private boolean controlarArray(String controlar, String[] array,int contador){
		for(int i=0;i<contador;i++)
			if(array[i].equals(controlar))
				return true;
		return false;
	}
	
}
